import { ALBUM, LRC, CHECK, URL, DETAIL,SONG_COMMENT } from '../api'
import {convert} from '../util'
import { useCallback } from 'react'

const defaultState = {
  songId: 0,//歌曲id
  songName: "",//歌曲名称
  singer: [{ id: 0, name: '' }],//歌手列表
  singerPicUrl: '',//歌手照片
  albumId: 0,//专辑id
  albumName: '',//专辑名称
  albumPicUrl: '',//专辑logo
  url: '',//歌曲播放地址
  isCheck: {//版权检测
    success: true,
    message: ''
  },
  lyric: [],//歌词
  hotComment:[]//热门评论

}

/**
 * 播放页store
 */

export default (state = defaultState, action) => {
  switch (action.type) {
    case 'IS_CHECK':
      return { ...state, isCheck: action.isCheck }
    case 'DETAIL':
      return {
        ...state,
        songId: action.songId,
        songName: action.songName,
        singer: action.singer,
        albumId: action.albumId,
        albumName: action.albumName,
        albumPicUrl: action.albumPicUrl
      }
    case 'SINGER_PIC':
      return { ...state, singerPicUrl: action.singerPicUrl }
    case 'URL':
      return { ...state, url: action.url }
    case 'LYRIC':
      return {...state,lyric:action.lrc}
    case 'COMMENT':
      return {...state,hotComment:action.hotComment}
    default:
      return state;

  }
}

//加载专辑信息
export const loadAlbum = (id) => (dispatch) => {
  fetch(ALBUM + id).then(response => response.json()).then(result => {
    console.log(result)

    dispatch({
      type: 'SINGER_PIC',
      singerPicUrl: result.album.artist.picUrl
    })
  })
}

//加载播放地址
export const loadUrl = (id) => (dispatch) => {
  fetch(URL + id).then(response => response.json()).then(result => {
    dispatch({
      type: 'URL',
      url: result.data[0].url
    })

  })
}

// 能否播放
export const checkSong = (id) => (dispatch) => {
  fetch(CHECK + id).then(response => response.json()).then(result => {

    dispatch({
      type: 'IS_CHECK',
      isCheck: result
    })

  })
}

// 加载歌词
export const loadLyric = (id) => (dispatch) => {
  fetch(LRC + id).then(response => response.json()).then(result => {
    if(!result.lrc){
      //纯音乐 没有歌词的情况下
      dispatch({
        type:'LYRIC',
        lrc:[{time:0,words:'纯音乐'}]
      })
      return;
    }
    let lrc = result.lrc.lyric;
    let arr = lrc.split('\n')//根据换行符分隔成数组
    let len = arr.length
    let results = [];// 存放处理好的 歌词和时间轴
    for (let i = 0; i < len; i++){
      let index = arr[i].lastIndexOf(']');// 找到最后一个 ] 的位置 作为歌词与时间轴的分界线
      let  time  = arr[i].substring(1,index);//时间轴是从1到分界线之前的位置
      let words = arr[i].substring(index+1);//歌词是分界线的下一个位置开始到结尾、

       // 时间轴分两种情况
        //1 情况一： 一句词对应一个时间轴 
        //2 情况二： 一句词对应两个时间轴  重复唱的歌词
      if (time !== '' && words !== '' && time.indexOf(']')===-1) {
        //情况一
        results.push({
          time:convert(time), 
          words
        })
      }else{
        // 情况二
        if(words!==''){
          // 继续用 ][ 再次分割时间轴
          let times = time.split('][');

          // 遍历多个时间轴 这多个时间轴对饮的是同一句歌词
          times.forEach((t)=>{
            // 给新的数组push的时候 就是多条记录 时间轴不同 但是歌词相同
            results.push({
              time:convert(t),
              words
            })
          })
        }
      }
    }

    // 对歌词排序
    results.sort((a,b)=>{
      return a.time - b.time;
    })

    dispatch({
      type:'LYRIC',
      lrc:results
    })

  })
}

//歌曲详情
export const loadDetail = (id) => (dispatch) => {
  fetch(DETAIL + id).then(response => response.json()).then(result => {

    let song = result.songs[0]
    dispatch({
      type: 'DETAIL',
      songId: song.id,
      songName: song.name,
      singer: song.ar,
      albumId: song.al.id,
      albumName: song.al.name,
      albumPicUrl: song.al.picUrl

    })
  })
}

//歌曲详情
export const songComment = (audioId,callback)=> async (dispatch)=>{
  let data = await fetch(SONG_COMMENT+audioId);
  let jsonData = await data.json();
  console.log(jsonData)
  callback()
  dispatch({
    type:'COMMENT',
    hotComment:jsonData.hotComments
  })
}